package org.jeecg.modules.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.modules.oms.entity.*;
import org.jeecg.modules.oms.parser.WindowConfirmationFileParser;
import org.jeecg.modules.oms.parser.WindowConfirmationFileParserFactory;
import org.jeecg.modules.oms.service.*;
import org.jeecg.modules.oms.vo.ProductSalesOrderPageVO;
import org.jeecg.modules.oms.vo.ProductSalesOrderVO;
import org.jeecg.modules.oms.vo.SummaryFileParseResultVO;
import org.jeecg.modules.oms.vo.WindowConfirmationFileVO;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.apache.catalina.connector.ClientAbortException;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;

/**
 * 成品销售订单控制器
 */
@Slf4j
@Api(tags = "成品销售订单")
@RestController
@RequestMapping("/oms/productSalesOrder")
public class ProductSalesOrderController extends JeecgController<ProductSalesOrder, IProductSalesOrderService> {

    @Autowired
    private IProductSalesOrderService productSalesOrderService;

    @Autowired
    private IProductSalesOrderDetailService productSalesOrderDetailService;

    @Autowired
    private IProductSalesOrderTransactionService productSalesOrderTransactionService;

    @Autowired
    private IProductSalesOrderProgressService productSalesOrderProgressService;

    @Autowired
    private ISysEmployeeService sysEmployeeService;

    @Value("${jeecg.path.upload}")
    private String uploadPath;

    @Autowired
    private ICfWindowDataService cfWindowDataService;

    @Autowired
    private ICfAccessoriesTableService cfAccessoriesTableService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IXingeProfileMaterialService xingeProfileMaterialService;

    @Autowired
    private ICfProfileMaterialService cfProfileMaterialService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "成品销售订单-分页列表查询")
    @ApiOperation(value = "成品销售订单-分页列表查询", notes = "成品销售订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ProductSalesOrder>> queryPageList(ProductSalesOrder productSalesOrder,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        Page<ProductSalesOrder> page = new Page<>(pageNo, pageSize);
        ProductSalesOrderPageVO queryVO = new ProductSalesOrderPageVO();
        // 将 productSalesOrder 的属性复制到 queryVO
        BeanUtils.copyProperties(productSalesOrder, queryVO);
        // 调用 service 层的 getProductSalesOrderPageList 方法
        IPage<ProductSalesOrder> pageList = productSalesOrderService.getProductSalesOrderPageList(page, queryVO);
        return Result.OK(pageList);
    }

    /**
     * 获取已审批通过的订单列表
     */
    @AutoLog(value = "成品销售订单-获取已审批通过的订单列表")
    @GetMapping("/approvedList")
    public Result<IPage<ProductSalesOrderVO>> getApprovedOrderList(ProductSalesOrder productSalesOrder,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                   @RequestParam(name = "customerProvince", required = false) String customerProvince,
                                                                   @RequestParam(name = "customerCity", required = false) String customerCity,
                                                                   @RequestParam(name = "customerDistrict", required = false) String customerDistrict,
                                                                   @RequestParam(name = "projectName", required = false) String projectName,
                                                                   @RequestParam(name = "projectProvince", required = false) String projectProvince,
                                                                   @RequestParam(name = "projectCity", required = false) String projectCity,
                                                                   @RequestParam(name = "projectDistrict", required = false) String projectDistrict,
                                                                   @RequestParam(name = "orderStatus", required = false) Integer orderStatus) {
        if (customerProvince != null && !customerProvince.isEmpty()) {
            productSalesOrder.setCustomerProvince(customerProvince);
        }
        if (customerCity != null && !customerCity.isEmpty()) {
            productSalesOrder.setCustomerCity(customerCity);
        }
        if (customerDistrict != null && !customerDistrict.isEmpty()) {
            productSalesOrder.setCustomerDistrict(customerDistrict);
        }
        if (projectName != null && !projectName.isEmpty()) {
            productSalesOrder.setProjectName(projectName);
        }
        if (projectProvince != null && !projectProvince.isEmpty()) {
            productSalesOrder.setProjectProvince(projectProvince);
        }
        if (projectCity != null && !projectCity.isEmpty()) {
            productSalesOrder.setProjectCity(projectCity);
        }
        if (projectDistrict != null && !projectDistrict.isEmpty()) {
            productSalesOrder.setProjectDistrict(projectDistrict);
        }
        if (orderStatus != null) {
            productSalesOrder.setStatus(orderStatus);
        }

        Page<ProductSalesOrderVO> page = new Page<>(pageNo, pageSize);
        IPage<ProductSalesOrderVO> pageList = productSalesOrderService.pageApprovedOrders(page, productSalesOrder);
        return Result.OK(pageList);
    }

    /**
     * 获取订单详情
     */
    @AutoLog(value = "成品销售订单-获取订单详情")
    @GetMapping("/detail")
    public Result<ProductSalesOrderVO> getOrderDetail(@RequestParam(name = "id") String id) {
        ProductSalesOrderVO orderDetail = productSalesOrderService.getOrderDetail(id);
        return Result.OK(orderDetail);
    }


    /**
     * 取消已上传文件
     */
    @AutoLog(value = "成品销售订单-取消上传")
    @ApiOperation(value = "成品销售订单-取消上传", notes = "取消已上传的汇总单或优化单")
    @PostMapping(value = "/cancelUpload")
    public Result<?> cancelUpload(@RequestParam Map<String, String> params) {
        String orderId = params.get("orderId");
        String status = params.get("status");
        log.info("取消上传文件, orderId={}, status={}", orderId, status);

        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String operatorId = loginUser != null ? loginUser.getId() : null;

        // 查询订单信息
        ProductSalesOrder order = productSalesOrderService.getById(orderId);
        if (order == null) {
            log.error("订单不存在, orderId={}", orderId);
            return Result.error("订单不存在");
        }

        // 检查订单状态
        if (order.getStatus() != Integer.valueOf(status)) {
            log.error("订单状态不匹配, orderId={}, expectedStatus={}, actualStatus={}",
                    orderId, status, order.getStatus());
            return Result.error("订单状态已变更，请刷新页面");
        }

        int targetStatus;
        String changeReason;

        // 根据当前状态确定回退到的状态
        if (Integer.valueOf(status) == 2) { // 已上传汇总单
            targetStatus = 1; // 回退到审核通过-待上传
            changeReason = "设计人员取消汇总单上传";
        } else if (Integer.valueOf(status) == 3) { // 已上传优化单
            targetStatus = 2; // 回退到已上传汇总单状态
            changeReason = "设计人员取消优化单上传";

            // 如果是长风软件用户（不需要汇总单），则回退到审核通过状态
            SysEmployee employee = sysEmployeeService.getById(operatorId);
            if (employee != null && employee.getOptimizeSoftType() != null && employee.getOptimizeSoftType() == 0) {
                targetStatus = 1; // 回退到审核通过-待上传
            }
        } else {
            log.error("当前状态不支持取消上传, orderId={}, status={}", orderId, status);
            return Result.error("当前状态不支持取消上传操作");
        }

        // 删除已上传的文件
        boolean fileDeleted = false;
        try {
            if (Integer.valueOf(status) == 2) { // 删除汇总单
                fileDeleted = productSalesOrderService.deleteSummaryFile(orderId);
            } else if (Integer.valueOf(status) == 3) { // 删除优化单
                fileDeleted = productSalesOrderService.deleteOptimizationFile(orderId);
            }
        } catch (Exception e) {
            log.error("删除文件失败, orderId={}, status={}", orderId, status, e);
            return Result.error("删除文件失败: " + e.getMessage());
        }

        if (!fileDeleted) {
            log.warn("文件不存在或已被删除, orderId={}, status={}", orderId, status);
            // 继续执行状态更新，即使文件删除失败
        }

        // 更新订单状态
        boolean success = productSalesOrderService.updateOrderStatus(orderId, Integer.valueOf(status), targetStatus, operatorId, changeReason);

        if (success) {
            log.info("取消上传成功, orderId={}, oldStatus={}, newStatus={}", orderId, status, targetStatus);
            return Result.OK("取消上传成功");
        } else {
            log.error("取消上传失败, orderId={}", orderId);
            return Result.error("取消上传失败");
        }
    }

    /**
     * 添加
     */
    @AutoLog(value = "成品销售订单-添加")
    @ApiOperation(value = "成品销售订单-添加", notes = "成品销售订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ProductSalesOrderVO productSalesOrderVO) {
        // 校验订单编号唯一性
        if (productSalesOrderVO.getOrderNo() != null && !productSalesOrderVO.getOrderNo().isEmpty()) {
            ProductSalesOrder existOrder = productSalesOrderService.getProductSalesOrderByOrderNo(productSalesOrderVO.getOrderNo());
            if (existOrder != null) {
                return Result.error("订单编号已存在，请修改后重试！");
            }
        }

        boolean success = productSalesOrderService.addProductSalesOrder(productSalesOrderVO);
        if (success) {
            return Result.OK("添加成功！");
        } else {
            return Result.error("添加失败！");
        }
    }

    /**
     * 编辑
     */
    @AutoLog(value = "成品销售订单-编辑")
    @ApiOperation(value = "成品销售订单-编辑", notes = "成品销售订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ProductSalesOrderVO productSalesOrderVO) {
        // 校验订单编号唯一性（排除自身）
        if (productSalesOrderVO.getOrderNo() != null && !productSalesOrderVO.getOrderNo().isEmpty()) {
            ProductSalesOrder existOrder = productSalesOrderService.getProductSalesOrderByOrderNo(productSalesOrderVO.getOrderNo());
            if (existOrder != null && !existOrder.getId().equals(productSalesOrderVO.getId())) {
                return Result.error("订单编号已存在，请修改后重试！");
            }
        }

        boolean success = productSalesOrderService.editProductSalesOrder(productSalesOrderVO);
        if (success) {
            return Result.OK("编辑成功!");
        } else {
            return Result.error("编辑失败!仅待审核状态的订单可以编辑");
        }
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "成品销售订单-通过id删除")
    @ApiOperation(value = "成品销售订单-通过id删除", notes = "成品销售订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        log.info("开始删除成品销售订单，ID: {}", id);
        boolean success = productSalesOrderService.deleteProductSalesOrder(id);
        if (success) {
            log.info("成品销售订单删除成功，ID: {}", id);
            return Result.OK("删除成功! 已清除订单及相关的明细、交易记录、进度记录和窗型数据。");
        } else {
            log.error("成品销售订单删除失败，ID: {}", id);
            return Result.error("删除失败! 请检查订单是否存在或是否有权限删除。");
        }
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "成品销售订单-批量删除")
    @ApiOperation(value = "成品销售订单-批量删除", notes = "成品销售订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        log.info("开始批量删除成品销售订单，IDs: {}", ids);
        String[] idArray = ids.split(",");
        boolean success = productSalesOrderService.deleteBatchProductSalesOrder(idArray);
        if (success) {
            log.info("批量删除成品销售订单成功，共删除{}条记录", idArray.length);
            return Result.OK("批量删除成功！已清除所有订单及关联的明细、交易记录、进度记录和窗型数据。");
        } else {
            log.error("批量删除成品销售订单失败，IDs: {}", ids);
            return Result.error("批量删除失败！请检查订单是否存在或是否有权限删除。");
        }
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "成品销售订单-通过id查询")
    @ApiOperation(value = "成品销售订单-通过id查询", notes = "成品销售订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        ProductSalesOrderVO productSalesOrderVO = productSalesOrderService.getProductSalesOrderById(id);
        if (productSalesOrderVO == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(productSalesOrderVO);
    }

    /**
     * 获取订单详情（包含所有相关信息）
     */
    @AutoLog(value = "成品销售订单-获取订单详情")
    @ApiOperation(value = "成品销售订单-获取订单详情", notes = "成品销售订单-获取订单详情，包含订单基本信息、财务信息和产品明细")
    @GetMapping(value = "/getOrderDetailById")
    public Result<?> getOrderDetailById(@RequestParam(name = "id") String id) {
        try {
            // 获取订单基本信息
            ProductSalesOrderVO orderVO = productSalesOrderService.getProductSalesOrderById(id);
            if (orderVO == null) {
                return Result.error("未找到对应订单");
            }

            // 获取订单明细
            List<ProductSalesOrderDetail> detailList = productSalesOrderDetailService.getDetailListByOrderId(id);
            orderVO.setProductSalesOrderDetailList(detailList);

            // 返回完整的订单信息
            return Result.OK(orderVO);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 通过订单编号查询
     */
    @AutoLog(value = "成品销售订单-通过订单编号查询")
    @ApiOperation(value = "成品销售订单-通过订单编号查询", notes = "成品销售订单-通过订单编号查询")
    @GetMapping(value = "/queryByOrderNo")
    public Result<?> queryByOrderNo(@RequestParam(name = "orderNo") String orderNo) {
        ProductSalesOrder productSalesOrder = productSalesOrderService.getProductSalesOrderByOrderNo(orderNo);
        if (productSalesOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(productSalesOrder);
    }

    /**
     * 生成订单编号
     */
    @AutoLog(value = "成品销售订单-生成订单编号")
    @ApiOperation(value = "成品销售订单-生成订单编号", notes = "成品销售订单-生成订单编号")
    @GetMapping(value = "/generateOrderNo")
    public Result<?> generateOrderNo() {
        String orderNo = productSalesOrderService.generateOrderNo();
        return Result.OK(orderNo);
    }

    /**
     * 更新订单状态
     */
    @AutoLog(value = "成品销售订单-更新订单状态")
    @ApiOperation(value = "成品销售订单-更新订单状态", notes = "成品销售订单-更新订单状态")
    @PutMapping(value = "/updateOrderStatus")
    public Result<?> updateOrderStatus(@RequestParam(name = "id") String id,
                                       @RequestParam(name = "oldStatus", required = false) Integer oldStatus,
                                       @RequestParam(name = "newStatus") Integer newStatus,
                                       @RequestParam(name = "changeReason") String changeReason) {
        log.info("更新订单状态: id={}, oldStatus={}, newStatus={}, changeReason={}", id, oldStatus, newStatus, changeReason);
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String changePersonId = loginUser != null ? loginUser.getId() : null;

        // 查询订单信息，用于后续通知
        ProductSalesOrder order = productSalesOrderService.getById(id);
        if (order == null) {
            log.error("订单不存在, id={}", id);
            return Result.error("订单不存在！");
        }

        // 更新订单状态并记录变更原因
        log.info("开始调用service更新订单状态, id={}", id);
        boolean success = productSalesOrderService.updateOrderStatus(id, oldStatus, newStatus, changePersonId, changeReason);

        if (success) {
            log.info("订单状态更新成功, id={}, newStatus={}", id, newStatus);

            // 如果状态变更为审核通过-待上传(1)，并且有销售负责人，发送通知
            if (newStatus == 1 && order.getSalesPersonId() != null) {
                try {
                    log.info("发送审核通过通知给销售负责人, salesPersonId={}", order.getSalesPersonId());
                    // 通过系统API发送消息通知
                    MessageDTO messageDTO = new MessageDTO();
                    messageDTO.setTitle("订单审核通过通知");
                    messageDTO.setContent("您的订单" + order.getOrderNo() + "已通过审核，请及时跟进后续处理。");
                    messageDTO.setToUser(order.getSalesPersonId());
                    messageDTO.setFromUser("system");
                    messageDTO.setCategory("4"); // 系统通知类别

                    // 设置业务参数，用于打开关联的业务数据
//                    messageDTO.setBusType("order_audit_pass");
//                    messageDTO.setBusId(id);

                    sysBaseAPI.sendSysAnnouncement(messageDTO);
                    log.info("审核通过通知发送成功, orderId={}", id);
                } catch (Exception e) {
                    log.error("发送订单审核通过通知失败, orderId={}", id, e);
                }
            }

            // 如果是新增订单-待审核(0)状态，且changeReason包含驳回原因，也发送通知（前端会单独调用，这里只是额外保障）
            if (newStatus == 0 && changeReason.contains("驳回") && order.getSalesPersonId() != null) {
                try {
                    log.info("发送审核驳回通知给销售负责人, salesPersonId={}", order.getSalesPersonId());
                    // 发送审核驳回通知
                    MessageDTO messageDTO = new MessageDTO();
                    messageDTO.setTitle("订单审核驳回通知");
                    messageDTO.setContent("您的订单" + order.getOrderNo() + "审核未通过，原因：" + changeReason + "，请及时处理。");
                    messageDTO.setToUser(order.getSalesPersonId());
                    messageDTO.setFromUser("system");
                    messageDTO.setCategory("4"); // 系统通知类别

                    // 设置业务参数
//                    messageDTO.setBusType("order_audit_reject");
//                    messageDTO.setBusId(id);

                    sysBaseAPI.sendSysAnnouncement(messageDTO);
                    log.info("审核驳回通知发送成功, orderId={}", id);
                } catch (Exception e) {
                    log.error("发送订单审核驳回通知失败, orderId={}", id, e);
                }
            }

            return Result.OK("状态更新成功!");
        } else {
            log.error("订单状态更新失败, id={}", id);
            return Result.error("状态更新失败!");
        }
    }

    /**
     * 查询订单详情列表
     */
    @AutoLog(value = "成品销售订单-查询订单详情列表")
    @ApiOperation(value = "成品销售订单-查询订单详情列表", notes = "成品销售订单-查询订单详情列表")
    @GetMapping(value = "/detail/list")
    public Result<?> queryDetailList(@RequestParam(name = "orderId") String orderId) {
        List<ProductSalesOrderDetail> detailList = productSalesOrderDetailService.getDetailListByOrderId(orderId);
        return Result.OK(detailList);
    }

    /**
     * 查询订单交易记录列表
     */
    @AutoLog(value = "成品销售订单-查询订单交易记录列表")
    @ApiOperation(value = "成品销售订单-查询订单交易记录列表", notes = "成品销售订单-查询订单交易记录列表")
    @GetMapping(value = "/transaction/list")
    public Result<?> queryTransactionList(@RequestParam(name = "orderId") String orderId,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ProductSalesOrderTransaction> page = new Page<>(pageNo, pageSize);
        IPage<ProductSalesOrderTransaction> pageList = productSalesOrderTransactionService.getTransactionPageByOrderId(page, orderId);
        return Result.OK(pageList);
    }

    /**
     * 添加交易记录
     */
    @AutoLog(value = "成品销售订单-添加交易记录")
    @ApiOperation(value = "成品销售订单-添加交易记录", notes = "成品销售订单-添加交易记录")
    @PostMapping(value = "/transaction/add")
    public Result<?> addTransaction(@RequestBody ProductSalesOrderTransaction transaction) {
        boolean success = productSalesOrderTransactionService.addTransaction(transaction);
        if (success) {
            return Result.OK("添加交易记录成功！");
        } else {
            return Result.error("添加交易记录失败！");
        }
    }

    /**
     * 编辑交易记录
     */
    @AutoLog(value = "成品销售订单-编辑交易记录")
    @ApiOperation(value = "成品销售订单-编辑交易记录", notes = "成品销售订单-编辑交易记录")
    @RequestMapping(value = "/transaction/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> editTransaction(@RequestBody ProductSalesOrderTransaction transaction) {
        if (transaction.getId() == null) {
            return Result.error("交易记录ID不能为空");
        }

        // 检查交易记录是否存在
        ProductSalesOrderTransaction existTransaction = productSalesOrderTransactionService.getById(transaction.getId());
        if (existTransaction == null) {
            return Result.error("交易记录不存在，无法进行编辑");
        }

        boolean success = productSalesOrderTransactionService.editTransaction(transaction);
        if (success) {
            return Result.OK("编辑交易记录成功！");
        } else {
            return Result.error("编辑交易记录失败！");
        }
    }

    /**
     * 删除交易记录
     */
    @AutoLog(value = "成品销售订单-删除交易记录")
    @ApiOperation(value = "成品销售订单-删除交易记录", notes = "成品销售订单-删除交易记录")
    @DeleteMapping(value = "/transaction/delete")
    public Result<?> deleteTransaction(@RequestParam(name = "id") String id) {
        boolean success = productSalesOrderTransactionService.removeById(id);
        if (success) {
            return Result.OK("删除交易记录成功！");
        } else {
            return Result.error("删除交易记录失败！");
        }
    }

    /**
     * 查询订单进度记录列表
     */
    @AutoLog(value = "成品销售订单-查询订单进度记录列表")
    @ApiOperation(value = "成品销售订单-查询订单进度记录列表", notes = "成品销售订单-查询订单进度记录列表")
    @GetMapping(value = "/progress/list")
    public Result<?> queryProgressList(@RequestParam(name = "orderId") String orderId,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ProductSalesOrderProgress> page = new Page<>(pageNo, pageSize);
        IPage<ProductSalesOrderProgress> pageList = productSalesOrderProgressService.getProgressPageByOrderId(page, orderId);
        return Result.OK(pageList);
    }

    /**
     * 添加进度记录
     */
    @AutoLog(value = "成品销售订单-添加进度记录")
    @ApiOperation(value = "成品销售订单-添加进度记录", notes = "成品销售订单-添加进度记录")
    @PostMapping(value = "/progress/add")
    public Result<?> addProgress(@RequestBody ProductSalesOrderProgress progress) {
        boolean success = productSalesOrderProgressService.addProgress(progress);
        if (success) {
            return Result.OK("添加进度记录成功！");
        } else {
            return Result.error("添加进度记录失败！");
        }
    }

    /**
     * 编辑进度记录
     */
    @AutoLog(value = "成品销售订单-编辑进度记录")
    @ApiOperation(value = "成品销售订单-编辑进度记录", notes = "成品销售订单-编辑进度记录")
    @PutMapping(value = "/progress/edit")
    public Result<?> editProgress(@RequestBody ProductSalesOrderProgress progress) {
        // 校验参数
        if (progress.getId() == null) {
            return Result.error("进度记录ID不能为空");
        }

        // 检查进度记录是否存在
        ProductSalesOrderProgress existProgress = productSalesOrderProgressService.getById(progress.getId());
        if (existProgress == null) {
            return Result.error("进度记录不存在，无法进行编辑");
        }

        // 使用Service层的editProgress方法
        boolean success = productSalesOrderProgressService.editProgress(progress);
        if (success) {
            return Result.OK("编辑进度记录成功！");
        } else {
            return Result.error("编辑进度记录失败！");
        }
    }

    /**
     * 根据订单ID获取交易记录分页列表
     */
    @GetMapping("/transaction/pageByOrderId")
    public Result<IPage<ProductSalesOrderTransaction>> getTransactionPageByOrderId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orderId") String orderId) {
        Page<ProductSalesOrderTransaction> page = new Page<>(pageNo, pageSize);
        IPage<ProductSalesOrderTransaction> pageList = productSalesOrderTransactionService.getTransactionPageByOrderId(page, orderId);
        return Result.OK(pageList);
    }

    /**
     * 根据订单ID获取进度记录分页列表
     */
    @GetMapping("/progress/pageByOrderId")
    public Result<IPage<ProductSalesOrderProgress>> getProgressPageByOrderId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orderId") String orderId) {
        Page<ProductSalesOrderProgress> page = new Page<>(pageNo, pageSize);
        IPage<ProductSalesOrderProgress> pageList = productSalesOrderProgressService.getProgressPageByOrderId(page, orderId);
        return Result.OK(pageList);
    }

    /**
     * 上传窗型确认文件
     */
    @AutoLog(value = "成品销售订单-上传窗型确认文件")
    @ApiOperation(value = "成品销售订单-上传窗型确认文件", notes = "成品销售订单-上传窗型确认文件")
    @PostMapping(value = "/uploadWindowConfirmationFile")
    public Result<?> uploadWindowConfirmationFile(HttpServletRequest request) {
        try {
            // 获取当前登录用户
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = loginUser != null ? loginUser.getId() : "";

            // 获取当前员工的优化软件类型
            SysEmployee employee = sysEmployeeService.getById(userId);
            Integer optimizeSoftwareType = employee != null ? employee.getOptimizeSoftType() : 0;

            // 获取租户ID
            Integer tenantId = 0;
            if (tenantId == 0 && employee != null) {
                tenantId = employee.getTenantId();
            }

            // 获取上传的文件
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

            // 存储处理结果
            List<ProductSalesOrderDetail> detailList = new ArrayList<>();
            String fileUrl = "";

            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                MultipartFile file = entry.getValue();
                if (file == null || file.isEmpty()) {
                    continue;
                }

                // 获取文件名
                String fileName = file.getOriginalFilename();
                if (fileName == null) {
                    fileName = "unknown_file";
                }

                // 检查文件类型，仅支持Excel文件
                if (!fileName.toLowerCase().endsWith(".xlsx") && !fileName.toLowerCase().endsWith(".xls")) {
                    return Result.error("仅支持上传Excel文件(.xlsx, .xls)");
                }

                // 获取文件后缀
                String suffix = fileName.substring(fileName.lastIndexOf("."));

                // 生成新的文件名 源文件名+时间戳+文件后缀
                // 保留Excel文件的原始后缀
                String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + suffix;

                // 使用jeecg标准的文件保存路径
                String bizPath = "windowConfirmationFiles";
                String savePath = uploadPath + File.separator + bizPath + File.separator + newFileName;

                // 保存文件
                File saveFile = new File(savePath);
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                }
                file.transferTo(saveFile);

                // 使用jeecg标准的文件访问URL格式
                String dbPath = bizPath + "/" + newFileName;

                // 记录日志
                log.info("Excel文件保存路径: {}", savePath);
                log.info("Excel文件数据库路径: {}", dbPath);

                // 使用工厂模式获取对应的处理器
                WindowConfirmationFileParser parser = WindowConfirmationFileParserFactory.getParser(optimizeSoftwareType);

                // 解析Excel文件，提取产品明细，并传入租户ID
                detailList = parser.parseFile(saveFile, tenantId);

                // 为每个产品明细设置图片URL
                for (ProductSalesOrderDetail detail : detailList) {
                    if (detail.getPhotoUrl() != null && !detail.getPhotoUrl().isEmpty()) {
                        // 解析器已经处理好图片URL，这里只需记录日志
                        log.info("解析器返回的图片路径: {}, 窗号: {}", detail.getPhotoUrl(), detail.getWindowNo());
                    } else {
                        // 如果photoUrl为空，则设置为null，不使用默认图片路径
                        detail.setPhotoUrl(null);
                        log.info("未找到图片，设置photoUrl为null, 窗号: {}", detail.getWindowNo());
                    }
                }

                // 如果是长风优化软件类型，保存详细表格数据到对应的表中
                if (optimizeSoftwareType == WindowConfirmationFileParserFactory.OPTIMIZE_SOFTWARE_TYPE_CHANGFENG) {
                    for (ProductSalesOrderDetail detail : detailList) {
                        // 保存详细表格数据
                        cfWindowDataService.saveAllWindowData(detail);
                    }
                }
            }

            // 返回处理结果
            WindowConfirmationFileVO result = new WindowConfirmationFileVO();
            result.setFileUrl(fileUrl);
            result.setDetails(detailList);
            result.setOptimizeSoftwareType(optimizeSoftwareType);
            result.setParseStatus(true);
            result.setParseMessage("解析成功");

            // 获取并设置下单日期和交付日期信息
            if (!detailList.isEmpty()) {
                // 检查解析结果是否包含下单日期信息
                Map<String, Object> windowInfo = null;
                // 初始化extendMap，防止空指针异常
                if (detailList.get(0).getExtendMap() == null) {
                    detailList.get(0).setExtendMap(new HashMap<>());
                }

                if (detailList.get(0).getExtendMap().containsKey("windowInfo")) {
                    windowInfo = (Map<String, Object>) detailList.get(0).getExtendMap().get("windowInfo");
                }

                if (windowInfo != null) {
                    // 设置下单日期
                    if (windowInfo.containsKey("orderDate")) {
                        result.setOrderDate(windowInfo.get("orderDate").toString());
                    }

                    // 设置交付日期（完工日期）
                    if (windowInfo.containsKey("completionDate")) {
                        result.setDeliveryDate(windowInfo.get("completionDate").toString());
                    }

                    // 设置订单编号 - 先尝试从contractNo获取
                    if (windowInfo.containsKey("contractNo")) {
                        result.setOrderId(windowInfo.get("contractNo").toString());
                    } else {
                        // 如果contractNo不存在，则尝试从orderNo获取
                        if (windowInfo.containsKey("orderNo")) {
                            result.setOrderId(windowInfo.get("orderNo").toString());
                        }
                    }
                    
                    // 设置金额信息（门确认单专用）
                    if (windowInfo.containsKey("totalAmount")) {
                        result.setTotalAmount((BigDecimal) windowInfo.get("totalAmount"));
                    }
                    if (windowInfo.containsKey("receivedAmount")) {
                        result.setReceivedAmount((BigDecimal) windowInfo.get("receivedAmount"));
                    }
                    if (windowInfo.containsKey("unpaidAmount")) {
                        result.setUnpaidAmount((BigDecimal) windowInfo.get("unpaidAmount"));
                    }
                }
            }

            return Result.OK(result);
        } catch (Exception e) {
            log.error("上传窗型确认文件失败", e);
            return Result.error("上传窗型确认文件失败: " + e.getMessage());
        }
    }

    @AutoLog(value = "成品销售订单-获取订单汇总信息")
    @ApiOperation(value = "成品销售订单-获取订单汇总信息", notes = "成品销售订单-获取订单汇总信息，包含订单总数、总销售额、总成本、总利润")
    @GetMapping(value = "/summary")
    public Result<?> getOrderSummary(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String projectName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String beginDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String salesPersonId,
            @RequestParam(required = false) String customerProvince,
            @RequestParam(required = false) String customerCity,
            @RequestParam(required = false) String customerDistrict,
            @RequestParam(required = false) String projectProvince,
            @RequestParam(required = false) String projectCity,
            @RequestParam(required = false) String projectDistrict,
            @RequestParam(required = false) String projectArea,
            @RequestParam(required = false) String deliveryDate,
            @RequestParam(required = false) String payStatus,
            @RequestParam(required = false) BigDecimal minTotalAmount,
            @RequestParam(required = false) BigDecimal maxTotalAmount,
            @RequestParam(required = false) BigDecimal minTotalCost,
            @RequestParam(required = false) BigDecimal maxTotalCost,
            @RequestParam(required = false) BigDecimal minProfit,
            @RequestParam(required = false) BigDecimal maxProfit,
            @RequestParam(required = false) String productSeries) {
        try {
            // 创建查询对象
            ProductSalesOrderPageVO productSalesOrderPageVO = new ProductSalesOrderPageVO();
            productSalesOrderPageVO.setOrderNo(orderNo);
            productSalesOrderPageVO.setCustomerName(customerName);
            productSalesOrderPageVO.setProjectName(projectName);
            productSalesOrderPageVO.setStatus(status);
            productSalesOrderPageVO.setSalesPersonId(salesPersonId);
            productSalesOrderPageVO.setCustomerProvince(customerProvince);
            productSalesOrderPageVO.setCustomerCity(customerCity);
            productSalesOrderPageVO.setCustomerDistrict(customerDistrict);
            productSalesOrderPageVO.setProjectProvince(projectProvince);
            productSalesOrderPageVO.setProjectCity(projectCity);
            productSalesOrderPageVO.setProjectDistrict(projectDistrict);
            productSalesOrderPageVO.setProjectArea(projectArea);
            productSalesOrderPageVO.setMinTotalAmount(minTotalAmount);
            productSalesOrderPageVO.setMaxTotalAmount(maxTotalAmount);
            productSalesOrderPageVO.setMinTotalCost(minTotalCost);
            productSalesOrderPageVO.setMaxTotalCost(maxTotalCost);
            productSalesOrderPageVO.setMinProfit(minProfit);
            productSalesOrderPageVO.setMaxProfit(maxProfit);
            productSalesOrderPageVO.setProductSeries(productSeries);

            // 日期处理
            if (beginDate != null && !beginDate.isEmpty()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    productSalesOrderPageVO.setBeginDate(sdf.parse(beginDate));
                } catch (Exception e) {
                    log.warn("解析beginDate失败: {}", beginDate);
                }
            }

            if (endDate != null && !endDate.isEmpty()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    productSalesOrderPageVO.setEndDate(sdf.parse(endDate));
                } catch (Exception e) {
                    log.warn("解析endDate失败: {}", endDate);
                }
            }

            if (deliveryDate != null && !deliveryDate.isEmpty()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    productSalesOrderPageVO.setDeliveryDate(sdf.parse(deliveryDate));
                } catch (Exception e) {
                    log.warn("解析deliveryDate失败: {}", deliveryDate);
                }
            }

            // 获取订单汇总信息
            Map<String, Object> summaryData = productSalesOrderService.getProductSalesOrderSummary(productSalesOrderPageVO);
            return Result.OK(summaryData);
        } catch (Exception e) {
            log.error("获取订单汇总信息失败", e);
            return Result.error("获取订单汇总信息失败: " + e.getMessage());
        }
    }

    /**
     * 处理客户端中断连接异常
     */
    @ExceptionHandler(ClientAbortException.class)
    public void handleClientAbortException(ClientAbortException e) {
        log.warn("客户端中断了连接: {}", e.getMessage());
    }

    /**
     * 获取订单的型材清单和配件清单
     */
    @AutoLog(value = "成品销售订单-获取型材清单和配件清单")
    @ApiOperation(value = "成品销售订单-获取型材清单和配件清单", notes = "根据订单ID获取型材清单和配件清单")
    @GetMapping(value = "/getOrderMaterialsAndAccessories")
    public Result<?> getOrderMaterialsAndAccessories(@RequestParam(name = "orderId") String orderId) {
        try {
            log.info("获取订单型材清单和配件清单, orderId={}", orderId);

            // 获取订单信息
            ProductSalesOrder order = productSalesOrderService.getById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 获取订单明细ID列表
            List<ProductSalesOrderDetail> detailList = productSalesOrderDetailService.getDetailListByOrderId(orderId);
            List<String> detailIds = detailList.stream().map(ProductSalesOrderDetail::getId).collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();

            // 根据优化软件类型获取不同的数据
            if (order.getOptimizationSoftwareType() == 1) { // 新格尔
                // 获取型材清单
                List<XingeProfileMaterial> profileMaterials = xingeProfileMaterialService.getByOrderId(orderId);
                result.put("profileMaterials", profileMaterials);

                // 获取配件清单
                List<Map<String, Object>> accessories = new ArrayList<>();

                // 根据订单明细ID获取配件信息
                if (!detailIds.isEmpty()) {
                    for (String detailId : detailIds) {
                        List<Map<String, Object>> detailAccessories = cfWindowDataService.getXgeAccessoriesByDetailId(detailId);
                        accessories.addAll(detailAccessories);
                    }
                }

                result.put("accessories", accessories);

                log.info("新格尔订单型材清单数量: {}, 配件清单数量: {}",
                        profileMaterials != null ? profileMaterials.size() : 0,
                        accessories != null ? accessories.size() : 0);
            } else { // 长风
                // 获取长风型材清单
                QueryWrapper<CfProfileMaterial> materialQueryWrapper = new QueryWrapper<>();
                materialQueryWrapper.eq("order_id", orderId);
                List<CfProfileMaterial> cfProfileMaterials = cfProfileMaterialService.list(materialQueryWrapper);
                result.put("profileMaterials", cfProfileMaterials);

                // 获取长风配件清单
                List<Map<String, Object>> accessories = new ArrayList<>();

                // 根据订单明细ID获取配件信息
                if (!detailIds.isEmpty()) {
                    for (String detailId : detailIds) {
                        QueryWrapper<CfAccessoriesTable> accessoriesQueryWrapper = new QueryWrapper<>();
                        accessoriesQueryWrapper.eq("detail_id", detailId);
                        List<CfAccessoriesTable> cfAccessories = cfAccessoriesTableService.list(accessoriesQueryWrapper);

                        // 将CfAccessoriesTable转换为Map以保持与前端接口一致
                        for (CfAccessoriesTable accessory : cfAccessories) {
                            Map<String, Object> accessoryMap = new HashMap<>();
                            accessoryMap.put("id", accessory.getId());
                            accessoryMap.put("accessoryCode", accessory.getAccessoryCode());
                            accessoryMap.put("accessoryName", accessory.getAccessoryName());
                            accessoryMap.put("specification", accessory.getSpecification());
                            accessoryMap.put("quantity", accessory.getQuantity());
                            accessoryMap.put("unit", accessory.getUnit());
                            accessoryMap.put("brand", accessory.getBrand());

                            accessories.add(accessoryMap);
                        }
                    }
                }

                result.put("accessories", accessories);

                log.info("长风订单型材清单数量: {}, 配件清单数量: {}",
                        cfProfileMaterials != null ? cfProfileMaterials.size() : 0,
                        accessories != null ? accessories.size() : 0);
            }

            return Result.OK(result);
        } catch (Exception e) {
            log.error("获取订单型材清单和配件清单失败", e);
            return Result.error("获取订单型材清单和配件清单失败: " + e.getMessage());
        }
    }

    /**
     * 获取设计订单详情信息
     */
    @AutoLog(value = "成品销售订单-获取设计订单详情")
    @ApiOperation(value = "成品销售订单-获取设计订单详情", notes = "根据订单ID获取设计订单详情信息")
    @GetMapping(value = "/getDesignOrderDetail")
    public Result<?> getDesignOrderDetail(@RequestParam(name = "orderId") String orderId) {
        try {
            log.info("获取设计订单详情, orderId={}", orderId);

            // 获取订单信息
            ProductSalesOrderVO order = productSalesOrderService.getOrderDetail(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("orderNo", order.getOrderNo());
            result.put("customerName", order.getCustomerName());
            result.put("projectName", order.getProjectName());
            result.put("orderDate", order.getOrderDate());
            result.put("deliveryDate", order.getDeliveryDate());
            result.put("salesPersonId", order.getSalesPersonId());
            result.put("salesPersonName", order.getSalesPersonName());
            result.put("status", order.getStatus());
            result.put("optimizationSoftwareType", order.getOptimizationSoftwareType());
            result.put("hasSummaryFile", order.getHasSummaryFile());
            result.put("hasOptimizationFile", order.getHasOptimizationFile());
            result.put("detailList", order.getProductSalesOrderDetailList());

            return Result.OK(result);
        } catch (Exception e) {
            log.error("获取设计订单详情失败", e);
            return Result.error("获取设计订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 订单审核
     */
    @AutoLog(value = "成品销售订单-订单审核")
    @ApiOperation(value = "成品销售订单-订单审核", notes = "成品销售订单-订单审核")
    @PostMapping(value = "/audit")
    public Result<?> auditOrder(@RequestBody Map<String, Object> params) {
        try {
            log.info("订单审核，参数: {}", params);

            // 获取参数
            String id = (String) params.get("id");
            Integer auditResult = Integer.valueOf(params.get("auditResult").toString());
            String rejectReason = (String) params.get("rejectReason");
            String remark = (String) params.get("remark");

            // 参数校验
            if (id == null || id.isEmpty()) {
                return Result.error("订单ID不能为空");
            }

            if (auditResult == null) {
                return Result.error("审核结果不能为空");
            }

            // 如果是驳回，必须有驳回原因
            if (auditResult == 9 && (rejectReason == null || rejectReason.isEmpty())) {
                return Result.error("驳回订单必须填写驳回原因");
            }

            // 获取当前登录用户
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String operatorId = loginUser != null ? loginUser.getId() : null;
            String operatorName = loginUser != null ? loginUser.getRealname() : "系统";

            // 获取订单信息
            ProductSalesOrder order = productSalesOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }

            // 检查订单状态
            if (order.getStatus() != 0) {
                return Result.error("只能审核待审核状态的订单");
            }

            // 根据审核结果设置不同的状态和进度内容
            if (auditResult == 1) {
                // 更新订单状态为审核通过(1)
                boolean success = productSalesOrderService.updateOrderStatus(id, 0, 1, operatorId, "订单审核通过");
                if (!success) {
                    return Result.error("更新订单状态失败");
                }
            } else if (auditResult == 9) {
                // 更新订单状态为审核驳回(9)
                boolean success = productSalesOrderService.updateOrderStatus(id, 0, 9, operatorId, "订单审核驳回，原因：" + rejectReason);
                if (!success) {
                    return Result.error("更新订单状态失败");
                }
            } else {
                return Result.error("无效的审核结果");
            }

            // 如果是审核通过，并且有销售负责人，发送通知
            if (auditResult == 1 && order.getSalesPersonId() != null) {
                try {
                    log.info("发送审核通过通知给销售负责人, salesPersonId={}", order.getSalesPersonId());
                    // 通过系统API发送消息通知
                    MessageDTO messageDTO = new MessageDTO();
                    messageDTO.setTitle("订单审核通过通知");
                    messageDTO.setContent("您的订单" + order.getOrderNo() + "已通过审核，请及时跟进后续处理。");
                    messageDTO.setToUser(order.getSalesPersonId());
                    messageDTO.setFromUser("system");
                    messageDTO.setCategory("4"); // 系统通知类别

                    sysBaseAPI.sendSysAnnouncement(messageDTO);
                    log.info("审核通过通知发送成功, orderId={}", id);
                } catch (Exception e) {
                    log.error("发送订单审核通过通知失败, orderId={}", id, e);
                }
            }
            // 如果是审核驳回，并且有销售负责人，发送通知
            else if (auditResult == 9 && order.getSalesPersonId() != null) {
                try {
                    log.info("发送审核驳回通知给销售负责人, salesPersonId={}", order.getSalesPersonId());
                    // 发送审核驳回通知
                    MessageDTO messageDTO = new MessageDTO();
                    messageDTO.setTitle("订单审核驳回通知");
                    messageDTO.setContent("您的订单" + order.getOrderNo() + "审核未通过，原因：" + rejectReason + "，请及时处理。");
                    messageDTO.setToUser(order.getSalesPersonId());
                    messageDTO.setFromUser("system");
                    messageDTO.setCategory("4"); // 系统通知类别

                    sysBaseAPI.sendSysAnnouncement(messageDTO);
                    log.info("审核驳回通知发送成功, orderId={}", id);
                } catch (Exception e) {
                    log.error("发送订单审核驳回通知失败, orderId={}", id, e);
                }
            }

            return Result.OK("审核操作成功");
        } catch (Exception e) {
            log.error("订单审核失败", e);
            return Result.error("订单审核失败: " + e.getMessage());
        }
    }


    /**
     * 获取未生成余料入库单的订单列表
     */
    @AutoLog(value = "成品销售订单-获取未生成余料入库单的订单列表")
    @GetMapping("/getOrderListWithoutYuLiaoRuku")
    public Result<IPage<ProductSalesOrderVO>> getOrderListWithoutYuLiaoRuku() {
        try {
            // 查询未生成余料入库单的订单列表
            IPage<ProductSalesOrderVO> page = productSalesOrderService.getOrderListWithoutYuLiaoRuku();
            return Result.OK(page);
        } catch (Exception e) {
            log.error("获取未生成余料入库单的订单列表失败", e);
            return Result.error("获取未生成余料入库单的订单列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID列表获取订单信息（用于JSelectProductOrder组件）
     */
    @AutoLog(value = "成品销售订单-根据ID列表获取订单信息（用于组件）")
    @GetMapping("/listByIds")
    public Result<?> listByIds(@RequestParam(name = "ids") String ids) {
        try {
            if (StringUtils.isBlank(ids)) {
                return Result.error("订单ID不能为空");
            }

            List<String> idList = Arrays.asList(ids.split(","));
            List<ProductSalesOrder> orderList = productSalesOrderService.listByIds(idList);

            // 转换为VO对象，添加额外信息
            List<ProductSalesOrderVO> resultList = new ArrayList<>();
            for (ProductSalesOrder order : orderList) {
                ProductSalesOrderVO orderVO = new ProductSalesOrderVO();
                BeanUtils.copyProperties(order, orderVO);

                // 获取销售负责人姓名
                if (StringUtils.isNotBlank(order.getSalesPersonId())) {
                    SysEmployee employee = sysEmployeeService.getById(order.getSalesPersonId());
                    if (employee != null) {
                        orderVO.setSalesPersonName(employee.getEmpName());
                    }
                }

                resultList.add(orderVO);
            }

            return Result.OK(resultList);
        } catch (Exception e) {
            log.error("根据ID列表获取订单信息失败", e);
            return Result.error("获取订单信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID列表获取订单信息
     */
    @AutoLog(value = "成品销售订单-根据ID列表获取订单信息")
    @GetMapping("/getOrdersByIds")
    public Result<?> getOrdersByIds(@RequestParam(name = "ids") String ids) {
        try {
            if (StringUtils.isBlank(ids)) {
                return Result.error("订单ID不能为空");
            }

            String[] idArray = ids.split(",");
            List<ProductSalesOrderVO> orderList = new ArrayList<>();

            for (String id : idArray) {
                ProductSalesOrderVO order = productSalesOrderService.getOrderDetail(id);
                if (order != null) {
                    orderList.add(order);
                }
            }

            return Result.OK(orderList);
        } catch (Exception e) {
            log.error("根据ID列表获取订单信息失败", e);
            return Result.error("获取订单信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单明细列表
     */
    @AutoLog(value = "成品销售订单-获取订单明细列表")
    @GetMapping("/getOrderDetails")
    public Result<?> getOrderDetails(@RequestParam(name = "orderId") String orderId) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return Result.error("订单ID不能为空");
            }

            QueryWrapper<ProductSalesOrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            queryWrapper.orderByAsc("create_time");

            List<ProductSalesOrderDetail> detailList = productSalesOrderDetailService.list(queryWrapper);
            return Result.OK(detailList);
        } catch (Exception e) {
            log.error("获取订单明细失败", e);
            return Result.error("获取订单明细失败: " + e.getMessage());
        }
    }
}